package com.qihang.librarymanage.jframe.user;

import com.qihang.librarymanage.dao.BorrowDetailDao;
import com.qihang.librarymanage.dao.UserDao;
import com.qihang.librarymanage.pojo.BookBorrowDetail;
import com.qihang.librarymanage.pojo.BorrowDetail;
import com.qihang.librarymanage.pojo.User;
import com.qihang.librarymanage.utils.DatabaseUtils;
import com.qihang.librarymanage.utils.Theme;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;

public class UserCenterPage extends JFrame {
    private User user;
    private JPanel mainPanel;
    private JPanel userInfoPanel;
    private JPanel borrowHistoryPanel;
    private JPanel statisticsPanel;
    private JTabbedPane tabbedPane;
    private DefaultTableModel borrowTableModel;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;
    private JTextField phoneField;

    public UserCenterPage(User user) {
        // 添加对用户对象为空的检查
        if (user == null) {
            JOptionPane.showMessageDialog(null, "用户信息不存在，请先登录", "错误", JOptionPane.ERROR_MESSAGE);
            dispose();
            new BookSearch();
            return;
        }
        
        this.user = user;
        
        // 应用主题
        new Theme(1);
        
        // 设置窗口属性
        setTitle("个人中心");
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 创建主面板
        mainPanel = new JPanel(new BorderLayout());
        
        // 创建顶部面板
        JPanel headerPanel = createHeaderPanel();
        mainPanel.add(headerPanel, BorderLayout.NORTH);
        
        // 创建选项卡面板
        tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        
        // 创建"个人信息"面板
        userInfoPanel = createUserInfoPanel();
        tabbedPane.addTab("个人信息", null, userInfoPanel, "查看和修改个人信息");
        
        // 创建"借阅记录"面板
        borrowHistoryPanel = createBorrowHistoryPanel();
        tabbedPane.addTab("借阅记录", null, borrowHistoryPanel, "查看借阅历史");
        
        // 创建"借阅统计"面板
        statisticsPanel = createStatisticsPanel();
        tabbedPane.addTab("借阅统计", null, statisticsPanel, "查看借阅统计信息");
        
        mainPanel.add(tabbedPane, BorderLayout.CENTER);
        
        // 创建底部面板
        JPanel footerPanel = createFooterPanel();
        mainPanel.add(footerPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
        setVisible(true);
    }
    
    private JPanel createHeaderPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setPreferredSize(new Dimension(1000, 100));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 10, 20));
        
        JLabel titleLabel = new JLabel("个人中心");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        panel.add(titleLabel, BorderLayout.CENTER);
        
        JLabel welcomeLabel = new JLabel("欢迎您，" + user.getUserName());
        welcomeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        welcomeLabel.setHorizontalAlignment(JLabel.RIGHT);
        panel.add(welcomeLabel, BorderLayout.EAST);
        
        return panel;
    }
    
    private JPanel createUserInfoPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(null);  // 使用绝对布局
        
        // 左侧信息展示区
        JPanel leftPanel = new JPanel();
        leftPanel.setBounds(50, 50, 400, 350);
        leftPanel.setBorder(BorderFactory.createTitledBorder("基本信息"));
        leftPanel.setLayout(null);
        
        // 显示用户基本信息
        int labelWidth = 80;
        int fieldWidth = 250;
        int height = 30;
        int gap = 40;
        int startY = 50;
        
        // 账号
        JLabel accountLabel = new JLabel("账号：");
        accountLabel.setBounds(30, startY, labelWidth, height);
        accountLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(accountLabel);
        
        JTextField accountField = new JTextField(user.getUserAccount());
        accountField.setBounds(110, startY, fieldWidth, height);
        accountField.setEditable(false);
        accountField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(accountField);
        
        // 用户名
        JLabel nameLabel = new JLabel("姓名：");
        nameLabel.setBounds(30, startY + gap, labelWidth, height);
        nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(nameLabel);
        
        JTextField nameField = new JTextField(user.getUserName());
        nameField.setBounds(110, startY + gap, fieldWidth, height);
        nameField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(nameField);
        
        // 性别
        JLabel sexLabel = new JLabel("性别：");
        sexLabel.setBounds(30, startY + gap*2, labelWidth, height);
        sexLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(sexLabel);
        
        JComboBox<String> sexComboBox = new JComboBox<>(new String[]{"女", "男"});
        sexComboBox.setSelectedIndex(user.getSex());
        sexComboBox.setBounds(110, startY + gap*2, fieldWidth, height);
        sexComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(sexComboBox);
        
        // 电话
        JLabel phoneLabel = new JLabel("电话：");
        phoneLabel.setBounds(30, startY + gap*3, labelWidth, height);
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(phoneLabel);
        
        phoneField = new JTextField(user.getPhone());
        phoneField.setBounds(110, startY + gap*3, fieldWidth, height);
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        leftPanel.add(phoneField);
        
        // 保存基本信息按钮
        JButton saveInfoButton = new JButton("保存基本信息");
        saveInfoButton.setBounds(110, startY + gap*4, fieldWidth, height+10);
        saveInfoButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        saveInfoButton.addActionListener(e -> saveUserInfo(nameField.getText(), sexComboBox.getSelectedIndex(), phoneField.getText()));
        leftPanel.add(saveInfoButton);
        
        panel.add(leftPanel);
        
        // 右侧修改密码区
        JPanel rightPanel = new JPanel();
        rightPanel.setBounds(500, 50, 400, 350);
        rightPanel.setBorder(BorderFactory.createTitledBorder("修改密码"));
        rightPanel.setLayout(null);
        
        // 新密码
        JLabel newPasswordLabel = new JLabel("新密码：");
        newPasswordLabel.setBounds(30, 70, labelWidth, height);
        newPasswordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        rightPanel.add(newPasswordLabel);
        
        newPasswordField = new JPasswordField();
        newPasswordField.setBounds(110, 70, fieldWidth, height);
        newPasswordField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        rightPanel.add(newPasswordField);
        
        // 确认密码
        JLabel confirmLabel = new JLabel("确认密码：");
        confirmLabel.setBounds(30, 130, labelWidth+20, height);
        confirmLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        rightPanel.add(confirmLabel);
        
        confirmPasswordField = new JPasswordField();
        confirmPasswordField.setBounds(110, 130, fieldWidth, height);
        confirmPasswordField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        rightPanel.add(confirmPasswordField);
        
        // 修改密码按钮
        JButton changePasswordButton = new JButton("修改密码");
        changePasswordButton.setBounds(110, 190, fieldWidth, height+10);
        changePasswordButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        changePasswordButton.addActionListener(e -> changePassword());
        rightPanel.add(changePasswordButton);
        
        panel.add(rightPanel);
        
        return panel;
    }
    
    private JPanel createBorrowHistoryPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        
        JLabel statusLabel = new JLabel("借阅状态：");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        filterPanel.add(statusLabel);
        
        JComboBox<String> statusComboBox = new JComboBox<>(new String[]{"全部", "在借", "已还"});
        statusComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        statusComboBox.setPreferredSize(new Dimension(120, 35));
        filterPanel.add(statusComboBox);
        
        JTextField searchField = new JTextField();
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        searchField.setPreferredSize(new Dimension(200, 35));
        filterPanel.add(searchField);
        
        JButton searchButton = new JButton("搜索");
        searchButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        searchButton.setPreferredSize(new Dimension(80, 35));
        searchButton.addActionListener(e -> {
            int status = -1; // 全部
            if (statusComboBox.getSelectedIndex() == 1) {
                status = 0; // 在借
            } else if (statusComboBox.getSelectedIndex() == 2) {
                status = 1; // 已还
            }
            loadBorrowHistory(searchField.getText(), status);
        });
        filterPanel.add(searchButton);
        
        panel.add(filterPanel, BorderLayout.NORTH);
        
        // 创建表格
        String[] columnNames = {"编号", "书名", "状态", "借书时间", "还书时间"};
        borrowTableModel = new DefaultTableModel(null, columnNames);
        JTable borrowTable = new JTable(borrowTableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        // 设置表格样式
        borrowTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        borrowTable.setRowHeight(30);
        borrowTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 16));
        borrowTable.getTableHeader().setReorderingAllowed(false);
        
        // 文字居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        borrowTable.setDefaultRenderer(Object.class, centerRenderer);
        
        // 将表格添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(borrowTable);
        panel.add(scrollPane, BorderLayout.CENTER);
        
        // 初始加载所有借阅历史
        loadBorrowHistory("", -1);
        
        return panel;
    }
    
    private JPanel createStatisticsPanel() {
        JPanel panel = new JPanel(new BorderLayout(15, 15));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建统计卡片面板
        JPanel cardsPanel = new JPanel(new GridLayout(1, 3, 20, 0));
        
        // 借阅总数卡片
        JPanel totalBorrowPanel = createStatCard("借阅总数", getTotalBorrowCount(), new Color(70, 130, 180));
        cardsPanel.add(totalBorrowPanel);
        
        // 当前借阅卡片
        JPanel currentBorrowPanel = createStatCard("当前借阅", getCurrentBorrowCount(), new Color(60, 179, 113));
        cardsPanel.add(currentBorrowPanel);
        
        // 已归还卡片
        JPanel returnedPanel = createStatCard("已归还", getReturnedCount(), new Color(255, 140, 0));
        cardsPanel.add(returnedPanel);
        
        panel.add(cardsPanel, BorderLayout.NORTH);
        
        // 创建借阅分析面板（这里可以放图表，但简单起见只放文字说明）
        JPanel analysisPanel = new JPanel();
        analysisPanel.setBorder(BorderFactory.createTitledBorder("借阅分析"));
        analysisPanel.setLayout(new BorderLayout());
        
        JTextArea analysisText = new JTextArea();
        analysisText.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        analysisText.setEditable(false);
        analysisText.setText("    您总共借阅了 " + getTotalBorrowCount() + " 本书籍。\n\n" +
                "    目前仍有 " + getCurrentBorrowCount() + " 本书在借阅中，已归还 " + getReturnedCount() + " 本。\n\n" +
                "    感谢您使用图书管理系统！");
        analysisText.setMargin(new Insets(20, 20, 20, 20));
        analysisText.setBackground(new Color(245, 245, 245));
        
        analysisPanel.add(analysisText, BorderLayout.CENTER);
        
        panel.add(analysisPanel, BorderLayout.CENTER);
        
        return panel;
    }
    
    private JPanel createStatCard(String title, int value, Color color) {
        JPanel card = new JPanel(new BorderLayout());
        card.setBorder(BorderFactory.createLineBorder(color, 2, true));
        card.setBackground(new Color(250, 250, 250));
        
        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(color);
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        titleLabel.setBorder(BorderFactory.createEmptyBorder(15, 0, 5, 0));
        
        JLabel valueLabel = new JLabel(String.valueOf(value));
        valueLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
        valueLabel.setHorizontalAlignment(JLabel.CENTER);
        valueLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 20, 0));
        
        card.add(titleLabel, BorderLayout.NORTH);
        card.add(valueLabel, BorderLayout.CENTER);
        
        return card;
    }
    
    private JPanel createFooterPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        panel.setPreferredSize(new Dimension(1000, 60));
        
        JButton backToHomeButton = new JButton("返回图书浏览");
        backToHomeButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        backToHomeButton.setPreferredSize(new Dimension(150, 40));
        backToHomeButton.addActionListener(e -> {
            dispose(); // 关闭当前窗口
            new BookInfo(user); // 返回图书浏览页面
        });
        panel.add(backToHomeButton);
        
        JButton goToSearchButton = new JButton("图书搜索");
        goToSearchButton.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        goToSearchButton.setPreferredSize(new Dimension(150, 40));
        goToSearchButton.addActionListener(e -> {
            dispose(); // 关闭当前窗口
            new BookSearch(); // 跳转到图书搜索页面
        });
        panel.add(goToSearchButton);
        
        return panel;
    }
    
    private void saveUserInfo(String userName, int sex, String phone) {
        if (userName.trim().isEmpty() || phone.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "姓名和电话不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 更新用户对象
        user.setUserName(userName);
        user.setSex(sex);
        user.setPhone(phone);
        
        // 保存到数据库
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            connection = connect.getConnection();
            UserDao userDao = new UserDao();
            boolean success = userDao.updateUser(connection, user);
            
            if (success) {
                JOptionPane.showMessageDialog(this, "个人信息更新成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "个人信息更新失败，请稍后重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "发生错误：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private void changePassword() {
        String newPassword = new String(newPasswordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());
        
        if (newPassword.isEmpty()) {
            JOptionPane.showMessageDialog(this, "密码不能为空！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次输入的密码不一致！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 更新用户密码
        user.setPassword(newPassword);
        
        // 保存到数据库
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            connection = connect.getConnection();
            UserDao userDao = new UserDao();
            boolean success = userDao.updateUserPassword(connection, user);
            
            if (success) {
                JOptionPane.showMessageDialog(this, "密码修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                newPasswordField.setText("");
                confirmPasswordField.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "密码修改失败，请稍后重试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "发生错误：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private void loadBorrowHistory(String bookName, int status) {
        // 清空表格
        borrowTableModel.setRowCount(0);
        
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            // 获取数据连接
            connection = connect.getConnection();
            BorrowDetailDao borrowDetailDao = new BorrowDetailDao();
            
            // 创建借阅详情对象
            BorrowDetail borrowDetail = new BorrowDetail();
            if (status != -1) { // -1表示全部
                borrowDetail.setStatus(status);
            }
            
            // 查询借阅记录
            ArrayList<BookBorrowDetail> bookBorrowDetails = borrowDetailDao.queryUserBorrowHistory(connection, borrowDetail, user, bookName);
            
            // 将数据库中查询到的数据加载到表格中
            for (BookBorrowDetail detail : bookBorrowDetails) {
                Vector<String> rowData = new Vector<>();
                rowData.add(String.valueOf(detail.getId()));
                rowData.add(detail.getBookName());
                rowData.add(detail.getStatus().equals("在借") ? "在借" : "已还");
                rowData.add(detail.getBorrowTime());
                rowData.add(detail.getReturnTime() == null ? "-" : detail.getReturnTime());
                borrowTableModel.addRow(rowData);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载借阅历史失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private int getTotalBorrowCount() {
        // 获取用户借阅总数
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            connection = connect.getConnection();
            BorrowDetailDao borrowDetailDao = new BorrowDetailDao();
            return borrowDetailDao.countUserBorrows(connection, user.getId(), -1); // -1表示全部
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private int getCurrentBorrowCount() {
        // 获取用户当前借阅数
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            connection = connect.getConnection();
            BorrowDetailDao borrowDetailDao = new BorrowDetailDao();
            return borrowDetailDao.countUserBorrows(connection, user.getId(), 0); // 0表示在借
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    private int getReturnedCount() {
        // 获取用户已还书数
        DatabaseUtils connect = new DatabaseUtils();
        Connection connection = null;
        try {
            connection = connect.getConnection();
            BorrowDetailDao borrowDetailDao = new BorrowDetailDao();
            return borrowDetailDao.countUserBorrows(connection, user.getId(), 1); // 1表示已还
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    // 主方法用于测试
    public static void main(String[] args) {
        // 创建一个测试用户
        User testUser = new User();
        testUser.setId(1);
        testUser.setUserAccount("test123");
        testUser.setUserName("测试用户");
        testUser.setSex(1);
        testUser.setPhone("13800138000");
        
        SwingUtilities.invokeLater(() -> new UserCenterPage(testUser));
    }
} 